package petertel.pbx.conf.extensions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import petertel.pbx.utils.ConfigItem;
import petertel.pbx.utils.ParserUtils;

public class Context {

	private ConfigItem config;

	public Context(ConfigItem config) {
		this.config = config;
	}

	public String getName() {
		return ParserUtils.getSectionName(config.getLine());
	}

	public Iterator<Extension> getExtensions() {
		List<Extension> list = new ArrayList<Extension>();
		Extension ext = new Extension();
		boolean isNew = true;
		ConfigItem child = null;
		for (Iterator<ConfigItem> iter = config.getChildren(); ext == null
				|| iter.hasNext();) {
			if (ext == null) {
				ext = new Extension();
				isNew = true;
			} else {
				child = iter.next();
			}
			BuildingStatus status = ext.build(child);
			if (status == BuildingStatus.accepted) {
				if (isNew) {
					list.add(ext);
					isNew = false;
				}
			} else if (status == BuildingStatus.ignored) {
				;
			} else if (status == BuildingStatus.rejected) {
				ext = null;
			} else {
				throw new RuntimeException("Unknown status: " + status);
			}
		}
		return list.iterator();
	}
}
